package com.hx;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author Huathy
 * @date 2021-10-11 23:32
 * @description
 */
public class ServerSocketDemo1 {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = null;
        Socket socket = null;
        try {
            //服务端一定需要监听一个端口，IP默认为本机地址
            serverSocket = new ServerSocket(8888);
            //接受客户端的连接（阻塞）
            socket = serverSocket.accept();
            //拿到输入流
            BufferedReader bis = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            System.out.println("client:" + bis.readLine());

            //获取输出流
            PrintWriter out = new PrintWriter(socket.getOutputStream(),true);
            //通过控制台获取信息
            BufferedReader sin = new BufferedReader(new InputStreamReader(System.in));
            String line = sin.readLine();
            while (!"bye".equalsIgnoreCase(line)){
                out.println(line);

                System.out.println("client:" + bis.readLine());
                line = sin.readLine();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(socket != null){
                socket.close();
            }
            if(serverSocket != null){
                serverSocket.close();
            }
        }
    }
}
